package com.abl.service.system.impl;

import com.abl.common.mybatis.dao.Dao;
import com.abl.common.mybatis.model.Dnt;
import com.abl.common.mybatis.strengthen.Wrapper;
import com.abl.domain.model.AblError;
import com.abl.domain.model.Param;
import com.abl.service.system.TemplateService;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 资源表实现
 */
@Slf4j
@Service
public class TemplateServiceImpl implements TemplateService {
    @Autowired
    private Dao dao;

    //新增
    @Override
    public boolean defaultTableAdd(Param<JSONObject> param) {
        //校验业务重复
        Wrapper<Object> qw = new Wrapper<>();
        qw.eq("d_s", 0);
        qw.eq("name", param.getString("name"));
        long a_template = dao.count("a_template", qw);
        if (a_template > 0) throw new AblError("操作失败：【名称:{0}】已经存在", param.getString("name"));

        //插入数据库
        Dnt dnt = Dnt.createInsert(param, "name", "type", "desc", "sort");
        dao.insert("a_template", dnt);

        return true;
    }

    //删除
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean defaultTableDel(Param<JSONObject> param) {
        //逻辑删除
        Wrapper<Object> uw = new Wrapper<>();
        uw.set("d_s", "1");
        uw.inNotBlank("id", param.getList("ids"));
        dao.update("a_template", uw);
        return true;
    }

    //修改
    @Override
    public long defaultTableEdit(Param<JSONObject> param) {
        param.checkNotNull("id", "name");

        //校验业务重复
        Wrapper<Object> qw = new Wrapper<>();
        qw.eq("d_s", 0);
        qw.eq("name", param.getString("name"));
        qw.ne("id", param.getString("id"));
        long a_template = dao.count("a_template", qw);
        if (a_template > 0) throw new AblError("操作失败：【名称:{0}】已经存在", param.getString("name"));

        Dnt dnt = Dnt.createUpdate(param);

        return dao.updateById("a_template", dnt);
    }

    //查询集合
    @Override
    public List<Dnt> defaultTableList(Param<JSONObject> param) {
        Wrapper<Object> qw = new Wrapper<>();
        qw.eq("d_s", 0);
        qw.eqNotBlank(param, "id", "type");
        qw.likeNotBlank("name", param.getString("name"));
        qw.orderByAsc("sort");

        if (param.isPage()) {
            return dao.page("a_template", qw, param.pageCurrent(), param.pageSize());
        } else {
            return dao.list("a_template", qw);
        }
    }

}
